package 线程池.ThreadTest;

/**
 * @author caihe
 * @date 2022/11/11 17:23
 */
public class InterruptTest {

    // 测试线程中断的效果
    public static void main(String[] args) throws InterruptedException {
        Object o = new Object();
        Thread threadA = new Thread(() -> {
            synchronized (o) {
                System.out.println("线程A获取锁");
                try {
                    // 将线程A放入对象o的等待集合中
                    o.wait();
                    System.out.println("线程A恢复" + Thread.currentThread().isInterrupted());
                } catch (InterruptedException e) {
                    System.out.println("线程A中断"  + Thread.currentThread().isInterrupted());
                }

            }

        }, "线程A");
        threadA.start();
        Thread threadB = new Thread(() -> {
            synchronized (o) {
                System.out.println("线程B获取锁");
                try {
                    // 将线程B放入对象o的等待集合中
                    o.wait();
                    System.out.println("线程B恢复"  + Thread.currentThread().isInterrupted());
                } catch (InterruptedException e) {
                    System.out.println("线程B中断"  + Thread.currentThread().isInterrupted());
                }

            }

        }, "线程B");
        threadB.start();
        
        Thread.sleep(100);
        
        new Thread(() -> {
            // 获取到对象o的监视器锁
            synchronized (o) {
                System.out.println("线程C获取锁");
                // 将线程A从对象0的等待集合中移除  移除后会重新获取监视器锁再抛出异常
                threadA.interrupt();
                o.notify();
                System.out.println("线程C调用了A的interrupt");
                System.out.println("线程B调用了notify");
            }
            
        }, "线程C").start();


        System.out.println();
        
    }
    
    
    
    
}
